package secret.hehe.com.secret.Activity;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.MessageService;
import secret.hehe.com.secret.Util.Util;

import static secret.hehe.com.secret.Util.Util.*;



public class MainActivity extends AppCompatActivity {

    private String userId;
    private String jsonString;
    private int icon;

    private String webUrl="file:///android_asset/html/mainPage.html";
    private WebView webView;
    private Toast mtoast;
    private String mailResult="";
    private String addressResult="";
    private int canClick = 1;

    private IntentFilter intentFilter;
    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;


    @Override
    public void onStart() {
        super.onStart();

        //接收本地广播
        localBroadcastManager = localBroadcastManager.getInstance(MainActivity.this);
        intentFilter = new IntentFilter("new_message");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        canClick = 1;
        //获取intent信息
        Intent intent = getIntent();
        try {
            userId=(String) intent.getSerializableExtra("userId");
            icon =(int) intent.getSerializableExtra("icon");
            if(userId==null)userId="0";
        }catch (Exception e){
            e.printStackTrace();
        }
        //防止杀死变量
        if (savedInstanceState != null) {
            try {
                icon = savedInstanceState.getInt("icon");
                userId = savedInstanceState.getString("userId");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //启动服务
        Intent service_intent = new Intent(MainActivity.this, MessageService.class);
        service_intent.putExtra("recvid", userId);
        startService(service_intent);
        //获取信息
        String mailParams = "recvid=" + userId;
        Util util = new Util();
        Util.postThread getAllMailThread = util.new postThread("/email/getEmail",getApplicationContext(),mailParams,handler,1);
        getAllMailThread.start();
        String addressParams="user1="+userId;
        Util.postThread getAllAddressThread = util.new postThread("/user/getAddress",getApplicationContext(),addressParams,handler,2);
        getAllAddressThread.start();


        //获取数据库信息
        String messageWhere = "recvid='"+userId+"' and isdel=0 order by sendtime desc";
        JSONArray jsonArray = doSelect("message",messageWhere,getApplicationContext());
        mailResult="{\"data\":"+jsonArray.toString()+"}";
        String addressWhere = "a.user1='"+userId+"' and a.user2=u.id and a.isscreen=0";
        addressResult="{\"data\":"+doSelect("user u,address a",addressWhere,getApplicationContext())+"}";

        webView=new WebView(getApplicationContext());
        RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.webview_container);
        startWebView(webView,webUrl,relativeLayout);
        webView.addJavascriptInterface(this, "android");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                loadMessage(mailResult);
                loadAddress(addressResult);
                refreshIcon(icon);
                Log.v("finish","完成");
                super.onPageFinished(view, url);
            }
        });

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(Environment.getExternalStorageDirectory())
                .append("/secret/")
                .append(userId)
                .append("/pic");
        //创建文件夹
        File folder=new File(stringBuilder.toString());
        if(!folder.exists()){
            folder.mkdirs();
        }

//        Handler x = new Handler();
//        x.postDelayed(new loadAllMessage(), 500);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(canClick ==1){
            canClick =0;
            switch (item.getItemId()) {
                case R.id.main_send: {//发送邮件
                    try {
                        Intent intent = new Intent(MainActivity.this, SendActivity.class);
                        intent.putExtra("sendId",userId);
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                case R.id.main_search: {//查找邮件
                    try {
                        Intent intent = new Intent(MainActivity.this, SearchMailActivity.class);
                        intent.putExtra("userId",userId);
                        intent.putExtra("isMail",1);
                        //intent.putExtra("result",mailResult);
                        startActivityForResult(intent,1000);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                case R.id.main_add: {//添加联系人
                    try {
                        toUpdateAddress("","","","0",0);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putInt("icon", icon);
        outState.putString("userId", userId);
    }

    @Override
    protected void onDestroy(){
        destroyWebView(webView);
        stopService(new Intent(MainActivity.this, MessageService.class));
        super.onDestroy();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //刷新信息
        super.onActivityResult(requestCode, resultCode, data);
        canClick = 1;
        if (requestCode == 1001 && resultCode == 1000) {
            //刷新通讯录
            String where = "a.user1='"+userId+"' and a.user2=u.id and a.isscreen=0";
            addressResult="{\"data\":"+doSelect("user u,address a",where,getApplicationContext())+"}";
            loadAddress(addressResult);
        }
        if (requestCode == 1001 && resultCode == 1002) {
            //刷新邮件
            String messageWhere = "recvid='"+userId+"' and isdel=0 order by sendtime desc";
            mailResult = "{\"data\":"+doSelect("message",messageWhere,getApplicationContext())+"}";
            loadMessage(mailResult);
        }
        if (requestCode == 1001 && resultCode == 1003) {
            //刷新头像
            try {
                icon = (int) data.getSerializableExtra("icon");
            }catch (Exception e){
                e.printStackTrace();
            }
            refreshIcon(icon);
        }
        if (requestCode == 1001 && resultCode == 1004) {
            try {
                icon = (int) data.getSerializableExtra("icon");
            }catch (Exception e){
                e.printStackTrace();
            }
            refreshIcon(icon);
            logoff();
        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //相应接受数据
            if (msg.what == 1) {
                //邮件相关
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));
                    if(code==200){//接收成功
                        JSONArray data = new JSONArray();
                        for(int i=0;i<jsonArray.length();i++)
                        {//存入数据库
                            jsonArray.getJSONObject(i).put("issend",1);
                            JSONObject json = (JSONObject)jsonArray.opt(i);
                            json.put("issend",1);
                            data.put(json);
                        }
                        doInsert("message",data,getApplicationContext());
                        String where = "recvid='"+userId+"' and isdel=0 order by sendtime desc";
                        mailResult="{\"data\":"+doSelect("message",where,getApplicationContext())+"}";
                        //loadMessage(result);
                    }else{
                        Toast.makeText(getApplicationContext(), "无邮件", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 0) {
                //无网络
                Toast.makeText(getApplicationContext(), "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
            if(msg.what ==2){
                //联系人相关
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));
                    if(code==200){//接收成功
                        JSONArray friendData = new JSONArray();
                        JSONArray addressData = new JSONArray();
                        for(int i=0;i<jsonArray.length();i++)
                        {//存入数据库
                            JSONObject json = (JSONObject)jsonArray.opt(i);
                        //更新好友信息
                            JSONObject friend = new JSONObject();
                            friend.put("id",json.getString("user2"));
                            friend.put("pwd","");
                            friend.put("icon",json.getString("icon"));
                            json.remove("icon");
                            friendData.put(friend);
                            addressData.put(json);
                        }
                        doUpdate("user",friendData,getApplicationContext());
                        doUpdate("address",addressData,getApplicationContext());
                        String where = "a.user1='"+userId+"' and a.user2=u.id and a.isscreen=0";
                        addressResult="{\"data\":"+doSelect("user u,address a",where,getApplicationContext())+"}";
                        //loadMessage(result);
                    }else{
                        Toast.makeText(getApplicationContext(), "无联系人", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    public void loadMessage(String json) {         //调用js
        webView.loadUrl("javascript:window.refreshMail("+json+")");
    }
    public void loadAddress(String json) {         //调用js
        webView.loadUrl("javascript:window.refreshAddress("+json+")");
    }
    public void refreshIcon(int json) {         //调用js切换内容
        webView.loadUrl("javascript:window.refreshIcon("+json+")");
    }

    @JavascriptInterface
    public void toMessage(String eid,int from) {//查看邮件
        try {
            Intent intent = new Intent(MainActivity.this, MessageActivity.class);
            intent.putExtra("userId",userId);
            intent.putExtra("eid",eid);
            intent.putExtra("from",from);
            startActivityForResult(intent,1001);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }
    @JavascriptInterface
    public void toSendMessage(String id) {//给通讯录发邮件
        try {
            Intent intent = new Intent(MainActivity.this, SendActivity.class);
            intent.putExtra("recvId",id);
            intent.putExtra("sendId",userId);
            startActivityForResult(intent,1001);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }
    @JavascriptInterface
    public void toUpdateAddress(String aid,String id,String name,String icon,int isUpdate) {//修改通讯录
        try {
            Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
            intent.putExtra("aid",aid);
            intent.putExtra("sendId",userId);
            intent.putExtra("recvId",id);
            intent.putExtra("name",name);
            intent.putExtra("icon",Integer.valueOf(icon).intValue());
            intent.putExtra("isUpdate",isUpdate);
            startActivityForResult(intent,1001);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void toUpdateUser() {//修改个人信息
        try {
            Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
            intent.putExtra("userId",userId);
            intent.putExtra("icon",icon);
            intent.putExtra("isUpdate",1);
            startActivityForResult(intent,1001);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }
    @JavascriptInterface
    public void clearImg() {//清空图片
        //判断是否有读写权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(MainActivity.this, "无法删除，请获取权限", Toast.LENGTH_SHORT).show();
        }else{
            new AlertDialog.Builder(MainActivity.this).setTitle("提示")
                    .setMessage("是否清空本账号保存的图片")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                StringBuilder stringBuilder = new StringBuilder();
                                stringBuilder.append(Environment.getExternalStorageDirectory())
                                        .append("/secret/")
                                        .append(userId)
                                        .append("/pic");
                                //创建文件夹
                                File file=new File(stringBuilder.toString());
                                if (file.isDirectory()) {
                                    File[] files = file.listFiles();
                                    for (int i = 0; i < files.length; i++) {
                                        File f = files[i];
                                        f.delete();
                                    }
                                    Toast.makeText(MainActivity.this, "已清空", Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    return;
                }
            }).setCancelable(false)
                    .show();
        }
    }
    @JavascriptInterface
    public void toCollection() {//查看收藏夹
        try {
            Intent intent = new Intent(MainActivity.this, SearchMailActivity.class);
            intent.putExtra("userId",userId);
            intent.putExtra("isMail",2);
            //intent.putExtra("result",mailResult);
            startActivityForResult(intent,1001);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }
    @JavascriptInterface
    public void logoff() {//注销
        new AlertDialog.Builder(MainActivity.this).setTitle("提示")
                .setMessage("退出登录将需要重新输入账号和密码")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("id",userId);
                            jsonObject.put("pwd","");
                            jsonObject.put("icon",icon);
                            JSONArray jsonArray =new JSONArray();
                            jsonArray.put(jsonObject);
                            doUpdate("user",jsonArray,getApplicationContext());
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                return;
            }
        }).setCancelable(false)
                .show();
    }
    @JavascriptInterface
    public String getUserId(){
        return userId;
    }
    @JavascriptInterface
    public String getIcon(String Icon){
        int icon = Integer.valueOf(Icon).intValue();
        String num="";
        if(icon<10)num="0";
        String url="file:///android_res/drawable/icon"+num+icon;
        return url;
    }
    @JavascriptInterface
    public String getResult(){
        return mailResult;
    }
    @JavascriptInterface
    public void alert(){
        if(mtoast == null){
            mtoast = Toast.makeText(MainActivity.this, "点击过快或网络访问出错", Toast.LENGTH_SHORT);
        }
        mtoast.show();

    }
    class loadAllMessage implements Runnable {
        public void run() {
            loadMessage(mailResult);
            loadAddress(addressResult);
            refreshIcon(icon);
        }

    }
    //广播接收器，接收服务返回的信息
    private class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int new_message = (int) intent.getSerializableExtra("new_message");
            if(new_message==0){
                String where = "recvid='"+userId+"' and isdel=0  order by sendtime desc";
                mailResult="{\"data\":"+doSelect("message",where,getApplicationContext())+"}";
                loadMessage(mailResult);
            }else{
                if(new_message%3==0){
                    Toast.makeText(MainActivity.this, "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
                }
            }

        }
    }


}